import logging
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from persons.models import Person
from persons.serializers import PersonBriefSerl, PersonLstSerl
import student
from student.auth import StudentJWT
from sms import views as smsapi
from ymiot import views as ymiodapi
from mgmt import pagination
from mgmt.models import Security
from mgmt.serializers import SecuritySerl
from student.models import StudentInvitePerson, StudentModel, StudentPerson
from student.models import StudentInvite
from student.models import StudentInviteVerify
from student.serializers import (
    StudentInviteDetSerl,
    StudentInviteLstSerl,
    StudentInvitePersonSerl,
    StudentPersonSerl,
    StudentSerl,
)
from teacher.models import TeacherModel
from teacher.serializers import TeacherBriefSerl, TeacherSerl


class IndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def get(self, request, format=None):
        code = 0
        msg = "OK"
        data = {}
        request_student = request.user
        data["student"] = StudentSerl(request_student).data
        # 安全等级
        security = Security.objects.get(pk=1)
        data["security"] = SecuritySerl(security).data
        # 我的邀约
        studentInviteList = (
            StudentInvite.objects.filter(student=request_student)
            .exclude(status__gte=8)
            .exclude(status=6)
        )
        if studentInviteList.count() == 0:
            data["inviteFlag"] = 0
        else:
            data["inviteFlag"] = 1
            data["invite"] = StudentInviteDetSerl(studentInviteList.last()).data
            main_person = studentInviteList.last().person
            invite_person_list = StudentInvitePerson.objects.filter(
                invite=studentInviteList.last()
            ).exclude(person=main_person)
            if invite_person_list.count() == 0:
                data["invitePersonFlag"] = 0
            else:
                data["invitePersonFlag"] = 1
                data["invitePersonList"] = StudentInvitePersonSerl(
                    invite_person_list, many=True
                ).data
        ret = {"code": code, "msg": msg, "data": data}
        return Response(ret)


class PersonListApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        student_person_list = StudentPerson.objects.filter(student=request_student).order_by("order")[:5]
        studentPersonList = []
        for student_person in student_person_list:
            studentPersonItem = {}
            studentPersonItem["id"] = student_person.id
            studentPersonItem["uuid"] = student_person.person.uuid
            studentPersonItem["name"] = student_person.person.name
            studentPersonItem["phone"] = student_person.person.phone
            studentPersonList.append(studentPersonItem)
        result["data"]["studentPersonList"] = studentPersonList
        return Response(result)


class PersonSearchApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        phone = request.GET.get("phone")
        try:
            person = Person.objects.get(phone=phone)
            result["data"]["oldPerson"] = PersonBriefSerl(person).data
        except Person.DoesNotExist:
            result["code"] = 404
            result["msg"] = "未找到该用户"
        return Response(result)


class PersonAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        dept = request.data["dept"]
        phone = request.data["phone"]
        name = request.data["name"]
        try:
            person = Person.objects.get(phone=phone)
        except Person.DoesNotExist:
            person = Person()
            person.phone = phone
            person.name = name
            person.dept = dept
            person.save()
        if not StudentPerson.objects.filter(
            student=request_student, person=person
        ).exists():
            student_person = StudentPerson()
            student_person.person = person
            student_person.student = request_student
            student_person.save()
        result["data"]["addPerson"] = {
            "uuid": person.uuid,
            "name": person.name,
            "phone": person.phone,
        }
        return Response(result)


class PersonBindApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        uuid = request.data["uuid"]
        try:
            person = Person.objects.get(uuid=uuid)
        except Person.DoesNotExist:
            result["code"] = 404
            result["msg"] = "未找到该用户"
            return Response(result)
        if not StudentPerson.objects.filter(
            student=request_student, person=person
        ).exists():
            student_person = StudentPerson()
            student_person.person = person
            student_person.student = request_student
            student_person.save()
        result["data"]["bindPerson"] = {
            "uuid": person.uuid,
            "name": person.name,
            "phone": person.phone,
        }
        return Response(result)


class TeacherListApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        teacher_list = TeacherModel.objects.filter(dept=request_student.dept)
        result["data"]["teacherList"] = TeacherBriefSerl(teacher_list, many=True).data
        return Response(result)


class InviteAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        teacher_id = request.data["teacher_id"]
        person_list = request.data["person_list"]
        what = request.data["what"]
        when = request.data["when"]
        # 找到main_person
        main_person = Person.objects.get(uuid=person_list[0]["uuid"])
        # 1.创建申请
        invite = StudentInvite()
        invite.student = request_student
        invite.person = main_person
        invite.when = when
        invite.what = what
        invite.status = 0
        invite.save()
        # 2.处理人员
        for person_item in person_list:
            person = Person.objects.get(uuid=person_item["uuid"])
            # 2.1 加入申请
            if not StudentInvitePerson.objects.filter(
                invite=invite, person=person
            ).exists():
                student_invite_person = StudentInvitePerson()
                student_invite_person.invite = invite
                student_invite_person.person = person
                student_invite_person.save()
            # 2.2 处理人员状态
            person.status = 1
            person.save()
            # 2.3 处理人员绑定
            if not StudentPerson.objects.filter(
                student=request_student, person=person
            ).exists():
                student_person = StudentPerson()
                student_person.person = person
                student_person.student = request_student
                student_person.save()
            else:
                student_person = StudentPerson.objects.filter(
                    student=request_student, person=person
                ).last()
            # 2.4 增加order
            student_person.order = student_person.order + 1
            student_person.save()
        # 处理申请审核
        teacher = TeacherModel.objects.get(id=teacher_id)
        student_invite_verify = StudentInviteVerify()
        student_invite_verify.invite = invite
        student_invite_verify.stage = 1
        student_invite_verify.teacher = teacher
        student_invite_verify.save()
        # 处理短信
        # smsvars = {
        #     'source': '访客{}'.format(apply.guest.name),
        # }
        # sendSms(1, teacher.phone, smsvars)
        return Response(result)


class InviteDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        # 申请详情
        invite_id = request.GET.get("invite_id")
        invite = StudentInvite.objects.get(id=invite_id)
        result["data"]["invite"] = StudentInviteDetSerl(invite).data
        main_person = invite.person
        result["data"]["mainPerson"] = PersonLstSerl(main_person).data
        #  人员
        student_invite_person_list = StudentInvitePerson.objects.filter(invite=invite)
        if student_invite_person_list.count() == 0:
            result["data"]["invitePersonFlag"] = 0
        else:
            result["data"]["invitePersonFlag"] = 1
            result["data"]["invitePersonList"] = StudentInvitePersonSerl(
                student_invite_person_list, many=True
            ).data
        # 审核列表
        invite_verify_list = (
            StudentInviteVerify.objects.filter(invite=invite)
            .exclude(status=0)
            .order_by("-updated")
        )
        verify_list = []
        for invite_verify in invite_verify_list:
            verify_item = {}
            verify_item["id"] = invite_verify.id
            verify_item["status"] = invite_verify.status
            verify_item["statusText"] = invite_verify.get_status_display()
            verify_item["stage"] = invite_verify.stage
            verify_item["stageText"] = invite_verify.get_stage_display()
            verify_item["teacher"] = invite_verify.teacher.name
            verify_item["describe"] = invite_verify.describe
            verify_item["updated"] = invite_verify.updated.strftime("%m-%d %H:%M")
            verify_list.append(verify_item)
        result["data"]["verifyList"] = verify_list
        return Response(result)


class InviteLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        # 申请
        student_invite_list = StudentInvite.objects.filter(student=request_student).order_by(
            "-updated"
        )
        invite_list = StudentInviteLstSerl(student_invite_list,many=True).data
        # for student_invite in student_invite_list:
        #     invite_item = StudentInviteLstSerl(student_invite).data
        #     # invite_item["id"] = invite.id
        #     # invite_item["guest"] = invite.guest.name
        #     # invite_item["guestDept"] = invite.guest.deptment
        #     # invite_item["guestPhone"] = invite.guest.phone
        #     # inviteItm["status"] = invite.status
        #     # inviteItm["statusText"] = invite.get_status_display()
        #     # inviteItm["when"] = invite.when.strftime("%m-%d %H:%M")
        #     # inviteItm["studentid"] = invite.student.id
        #     # inviteItm["studentDept"] = invite.student.deptment
        #     # inviteItm["studentName"] = invite.student.name
        #     # inviteItm["studentPhone"] = invite.student.phone
        #     invite_list.append(invite_item)
        # 1. 实例化分页器对象
        page_obj = pagination.PageNumberPagination()
        # 2. 使用自己配置的分页器调用分页方法进行分页
        page_data = page_obj.paginate_queryset(invite_list, request)
        # 4. 返回带上一页/下一页连接的页面
        return page_obj.get_paginated_response(page_data)


class InviteDelApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        # 申请详情
        invite_id = request.GET.get("invite_id")
        invite = StudentInvite.objects.get(id=invite_id)
        # 处理状态
        invite.status = 10
        invite.save()
        # 处理人员
        invite_person_list = StudentInvitePerson.objects.filter(invite=invite)
        for invite_person in invite_person_list:
            person = invite_person.person
            person.status = 0
            person.save()
        # 处理审核
        verifyList = StudentInviteVerify.objects.filter(invite=invite, status=0)
        for verifyItem in verifyList:
            verifyItem.status = 2
            verifyItem.describe = "访问被学生取消"
            verifyItem.save()
        return Response(result)


class InfoIndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [StudentJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_student = request.user
        result["data"]["student"] = StudentSerl(request_student).data
        # 安全等级
        security = Security.objects.get(pk=1)
        result["data"]["security"] = SecuritySerl(security).data
        # 访问申请
        student_invite_list = StudentInvite.objects.filter(student=request_student).order_by(
            "-updated"
        )
        result["data"]["inviteCount"] = student_invite_list.count()
        invite_list = student_invite_list[:5]
        result["data"]["inviteList"] = StudentInviteLstSerl(invite_list,many=True).data
        # inviteLst = []
        # for inviteItem in inviteList:
        #     inviteItm = {}
        #     inviteItm["id"] = inviteItem.id
        #     inviteItm["status"] = inviteItem.status
        #     inviteItm["statusText"] = inviteItem.get_status_display()
        #     inviteItm["guestId"] = inviteItem.guest.id
        #     inviteItm["guestName"] = inviteItem.guest.name
        #     inviteItm["guestDept"] = inviteItem.guest.deptment
        #     inviteItm["guestPhone"] = inviteItem.guest.phone
        #     inviteItm["when"] = inviteItem.when.strftime("%m-%d %H:%M")
        #     # visitor
        #     inviteItm["personCount"] = StudentInvitePerson.objects.filter(
        #         invite=inviteItem
        #     ).count()
        #     inviteLst.append(inviteItm)
        # data["inviteLst"] = inviteLst
        return Response(result)